// pages/translation/translation.js
const CryptoJS = require('../../miniprogram_npm/crypto-js/index');

Page({
  data: {
    sourceLanguage: '英文',
    targetLanguage: '中文',
    sourceLangCode: 'en',
    targetLangCode: 'zh-CHS',
    inputText: '',
    translationResult: '',
    translationHistory: []
  },

  onLoad: function(options) {
    this.loadTranslationHistory();
  },

  // 返回上一页
  goBack: function() {
    wx.navigateBack();
  },

  // 切换语言
  switchLanguages: function () {
    const sourceLanguage = this.data.sourceLanguage;
    const targetLanguage = this.data.targetLanguage;
    const sourceLangCode = this.data.sourceLangCode;
    const targetLangCode = this.data.targetLangCode;
  
    this.setData({
      sourceLanguage: targetLanguage,
      targetLanguage: sourceLanguage,
      sourceLangCode: targetLangCode,
      targetLangCode: sourceLangCode
    });
  },

  // 输入变化
  onInputChange: function(e) {
    this.setData({
      inputText: e.detail.value
    });
  },

  // 清空输入
  clearInput: function() {
    this.setData({
      inputText: '',
      translationResult: ''
    });
  },

  // 粘贴文本
  pasteText: function() {
    wx.getClipboardData({
      success: (res) => {
        this.setData({
          inputText: res.data
        });
      }
    });
  },

  // 翻译文本
  translateText: function () {
    const inputText = this.data.inputText.trim();

    if (!inputText) {
      wx.showToast({
        title: '请输入要翻译的内容',
        icon: 'none'
      });
      return;
    }

    wx.showLoading({
      title: '翻译中...'
    });

    const appKey = '4ffda8c18fdb77d9';
    const key = 'pMFXlst8tGJez0Htc1eGZpAHvwpjegnZ';
    const salt = Date.now();
    const curtime = Math.round(new Date().getTime() / 1000);
    const str1 = appKey + this.truncate(inputText) + salt + curtime + key;
    const sign = CryptoJS.SHA256(str1).toString(CryptoJS.enc.Hex);

    wx.request({
      url: 'https://openapi.youdao.com/api',
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        q: inputText,
        appKey: appKey,
        salt: salt,
        from: this.data.sourceLangCode,
        to: this.data.targetLangCode,
        sign: sign,
        signType: 'v3',
        curtime: curtime,
        vocabId: ''
      },
      success: (res) => {
        wx.hideLoading();
        console.log('翻译成功：', res.data);

        const result = res.data.translation ? res.data.translation[0] : '无翻译结果';

        this.setData({
          translationResult: result
        });

        this.saveTranslationHistory(inputText, result);
      },
      fail: (err) => {
        wx.hideLoading();
        console.error('请求失败', err);
        wx.showToast({
          title: '请求失败',
          icon: 'none'
        });
      }
    });
  },

  // 句子划段
  truncate(q) {
    const len = q.length;
    return len <= 20 ? q : q.substring(0, 10) + len + q.substring(len - 10);
  },

  // 模拟翻译
  mockTranslate: function(text) {
    const mockTranslations = {
      'hello': '你好',
      'world': '世界',
      'good morning': '早上好',
      'thank you': '谢谢你',
      'how are you': '你好吗',
      'i love you': '我爱你',
      'goodbye': '再见',
      '你好': 'hello',
      '世界': 'world',
      '早上好': 'good morning',
      '谢谢': 'thank you',
      '再见': 'goodbye'
    };

    const lowerText = text.toLowerCase();
    if (mockTranslations[lowerText]) {
      return mockTranslations[lowerText];
    }

    // 简单的模拟翻译
    if (this.data.sourceLanguage === '英文') {
      return `翻译结果：${text}（这是一个模拟的中文翻译）`;
    } else {
      return `Translation: ${text} (This is a mock English translation)`;
    }
  },

  // 保存翻译历史
  saveTranslationHistory: function(source, result) {
    let history = this.data.translationHistory;
    const newItem = {
      source: source,
      result: result,
      time: this.formatTime(new Date())
    };

    history.unshift(newItem);
    if (history.length > 10) {
      history = history.slice(0, 10); // 只保留最近10条
    }

    this.setData({
      translationHistory: history
    });

    // 保存到本地存储
    wx.setStorageSync('translationHistory', history);
  },

  // 加载翻译历史
  loadTranslationHistory: function() {
    const history = wx.getStorageSync('translationHistory') || [];
    this.setData({
      translationHistory: history
    });
  },

  // 格式化时间
  formatTime: function(date) {
    const now = new Date();
    const diff = now - date;
    const minutes = Math.floor(diff / 60000);
    
    if (minutes < 1) return '刚刚';
    if (minutes < 60) return `${minutes}分钟前`;
    
    const hours = Math.floor(minutes / 60);
    if (hours < 24) return `${hours}小时前`;
    
    const days = Math.floor(hours / 24);
    return `${days}天前`;
  },

  // 复制结果
  copyResult: function() {
    wx.setClipboardData({
      data: this.data.translationResult,
      success: function() {
        wx.showToast({
          title: '已复制到剪贴板',
          icon: 'success'
        });
      }
    });
  },

  // 分享结果
  shareResult: function() {
    if (!this.data.translationResult) {
      wx.showToast({
        title: '请先进行翻译',
        icon: 'none'
      });
      return;
    }
    
    // 构建分享内容：原文 + 翻译结果
    const shareContent = `${this.data.inputText}\n${this.data.translationResult}`;
    
    // 先保存分享数据到全局
    const app = getApp();
    app.globalData.shareData = {
      shareType: 'sentence',
      sentence: shareContent
    };
    
    // 跳转到study页面（tabBar页面需要使用switchTab）
    wx.switchTab({
      url: '/pages/study/study'
    });
  },

  // 选择历史项目
  selectHistoryItem: function(e) {
    const index = e.currentTarget.dataset.index;
    const item = this.data.translationHistory[index];
    this.setData({
      inputText: item.source,
      translationResult: item.result
    });
  }
})